package com.geetour.columbus.core.thread;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.geetour.columbus.common.model.LoginUser;

/**
 * @author ChenKai
 */
@SuppressWarnings("unchecked")
public class ThreadObjManager {

    private static final String COOKIE_LONGIN_ID = "cookieLoginId";
    private static final String PMS_THREADKEY_LOGINUSER = "pms_threadkey_loginuser";

    private static final ThreadLocal<Map> threadObjPool = new ThreadLocal<Map>();

    private static final Log log = LogFactory.getLog("login");


    /**
     * set the LoginUser threadObjPool
     * @param userObj
     */
    public static void setLoginUser(LoginUser userObj) {
        Map servletAttributesMap = threadObjPool.get();
        if (servletAttributesMap == null) {
            servletAttributesMap = new HashMap();
            threadObjPool.set(servletAttributesMap);
        }
        servletAttributesMap.put(PMS_THREADKEY_LOGINUSER, userObj);
    }

    /**
     * get the LoginUser from threadObjPool
     * @return
     */
    public static LoginUser getLoginUser() {
        LoginUser loginUser = null;
        String cookieUsername = null;
        Map servletAttributesMap = threadObjPool.get();
        if (servletAttributesMap != null) {
            loginUser = (LoginUser) servletAttributesMap.get(PMS_THREADKEY_LOGINUSER);
            cookieUsername = (String) servletAttributesMap.get(COOKIE_LONGIN_ID);
        }
        if (loginUser == null) {
            throw new RuntimeException("error:can not get LoginUser info...");
        }
        // check the cookie's loginId with the thread loginId
        if (cookieUsername != null && !cookieUsername.equals(loginUser.getUsername())) {
            try {
                throw new Exception("User should be " + cookieUsername + " but was " + loginUser.getUsername());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return loginUser;
    }

    /**
     * clear the threadObjPool map
     */
    public static void clear() {
        Map servletAttributesMap = threadObjPool.get();
        if (servletAttributesMap != null) {
            servletAttributesMap.clear();
        }
    }

    /**
     * set loginId from cookie
     * @param username
     */
    public static void setCookieUsername(String username) {
        Map servletAttributesMap = threadObjPool.get();
        if (servletAttributesMap == null) {
            servletAttributesMap = new HashMap();
            threadObjPool.set(servletAttributesMap);
        }
        servletAttributesMap.put(COOKIE_LONGIN_ID, username);
    }

}
